package com.totoro.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.totoro.exception.BusinessRuntimeException;
import com.totoro.exception.ResultCode;
import com.totoro.pojo.*;
import com.totoro.service.CartService;
import com.totoro.service.ProductService;
import com.totoro.service.ShopCouponService;
import com.totoro.utils.Base64EncryptionUtil;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author TOTORO
 * @date 2021/7/13 10:31
 */
@Controller
@RequestMapping("/cart_logic")
public class CartController {

    @Autowired
    CartService cartService;
    @Autowired
    ProductService productService;
    @Autowired
    ShopCouponService shopCouponService;


    /**
     * 将产品加入购物车
     * @param cart
     * @param session
     * @return
     */
    @RequestMapping(value = "/joinCart", method = RequestMethod.POST)
    @ResponseBody
    public String productJoinCart(Cart cart, HttpSession session){
        User user = (User) session.getAttribute("user");
        if(null == user){
            String beforeUrl = "/buy.htm?pid="+cart.getPid()+"&sid="+cart.getSid()+"&skuCode="+cart.getSkuId();
            return "/login.htm?ttr="+new String(Base64EncryptionUtil.base64Encrypt(beforeUrl));
        }

        cart.setUid(user.getUserId());
        System.out.println(cart.getUid()+"================");
        List<Integer> integers = cartService.findSameCartProductSku(cart);
        // 如果有了，叠加，否则新增一条购物车商品
        if(integers.size()!=0){
            cartService.updateCartProductCountByCartId(cart.getCount(), integers.get(0));
        } else{
            cartService.addCartProduct(cart);
        }
        // 获取购物车商品，存进session miniCart
        List<Product> productList = cartService.findCartProduct(user.getUserId());
        if(productList.size()>5){
            session.setAttribute("carts", productList.subList(0, 5));
        } else {
            session.setAttribute("carts", productList);
        }
        return "ok";
    }

    /**
     * 修改某个用户的购物车里某个商品的属性
     * @param cartId
     * @param skuId
     * @param count
     * @param session
     * @param model
     * @return
     */
    @SneakyThrows
    @RequestMapping(value = "/updateCpAttr", method = RequestMethod.POST)
    @ResponseBody
    public String updateCartProductSkuAndCount(@RequestParam("cartId") int cartId, @RequestParam(value = "skuId", required = false, defaultValue = "0") int skuId,
    @RequestParam(value = "count", required = false, defaultValue = "0") int count, HttpSession session, Model model) {
        User user = (User) session.getAttribute("user");
        cartService.updateCartProductAttrByUidAndPid(count, skuId, cartId);
        if(skuId !=0){
            // 判断修改的商品是否于其他满足条件的商品有一样的属性，如果有，则删除第一个 （真实的删除）
            Cart cart = cartService.findOneCartDataByCartId(cartId);
            List<Integer> integers = cartService.findSameCartProductSku(cart);
            if(integers.size() > 1){
                Integer isDelete = cartService.deleteCartRow(cartId);
                return "no";
            }
            // 返回当前sku属性的信息，判断修改的商品是否于其他满足条件的商品有一样的属性
            ProductSpecs productSpecs = productService.findAssignSkuByPidAndSkuId(skuId);
            ObjectMapper mapper = new ObjectMapper();
            return mapper.writeValueAsString(productSpecs);
        }
        return "yes!";
    }


    /**
     * 删除购物车某个商品，实现撤销技术
     * @param cartId
     * @param session
     * @return
     */
    @RequestMapping(value = "/deleteCartProduct", method = RequestMethod.POST)
    @ResponseBody
    public String deleteCartProduct(@RequestParam("cartId") int cartId, HttpSession session){
        User user = (User) session.getAttribute("user");
        // 先做一次验证
        Cart cart = cartService.findOneCartDataByCartId(cartId);
        if(cart.getUid() != user.getUserId()){
            throw new BusinessRuntimeException(ResultCode.DELETE_DATA_ERROR);
        }
        // 将该商品存进session再进行删除，实现撤销技术
        session.setAttribute("deleteCartProduct", cart);
        cartService.deleteCartRow(cartId);
        // 获取购物车商品，存进session
        List<Product> productList = cartService.findCartProduct(user.getUserId());
        if(productList.size()>5){
            session.setAttribute("carts", productList.subList(0, 5));
        } else {
            session.setAttribute("carts", productList);
        }
        return "delete success";
    }

    /**
     * 批量删除购物车商品
     * @param cartIds
     * @param session
     * @return
     */
    @RequestMapping(value = "/batchDeleteCartProduct", method = RequestMethod.POST)
    @ResponseBody
    public String batchDeleteCartProduct(@RequestParam("cartIds[]") Integer[] cartIds, HttpSession session){
        // 拿到需要删除的购物车实体
        List<Cart> carts = cartService.batchFindCartDataByCartId(cartIds);
        User user = (User) session.getAttribute("user");
        // 存进session
        session.setAttribute("batchDeleteCartProduct", carts);
        // 删除这些
        cartService.batchDeleteCartRow(cartIds);

        // 获取购物车商品，覆盖session
        List<Product> productList = cartService.findCartProduct(user.getUserId());
        if(productList.size()>5){
            session.setAttribute("carts", productList.subList(0, 5));
        } else {
            session.setAttribute("carts", productList);
        }
        return "delete success";
    }

    /**
     * 撤销前一次删除的商品
     * @param session
     * @return
     */
    @RequestMapping("/revokeDelete")
    public String revokeDeleteCartProduct(HttpSession session){
        Cart cart = (Cart) session.getAttribute("deleteCartProduct");
        User user = (User) session.getAttribute("user");
        if(null != cart){
            cartService.addCartProduct(cart);
        }
        List<Product> productList = cartService.findCartProduct(user.getUserId());
        if(productList.size()>5){
            session.setAttribute("carts", productList.subList(0, 5));
        } else {
            session.setAttribute("carts", productList);
        }
        return "redirect:/cart.htm";
    }

    /**
     * 批量撤销上一次删除的商品
     * @param session
     * @return
     */
    @RequestMapping("/batchRevokeDelete")
    public String batchRevokeDeleteCartProduct(HttpSession session){
        List<Cart> carts = (List<Cart>) session.getAttribute("batchDeleteCartProduct");
        User user = (User) session.getAttribute("user");
        if(null != carts && carts.size()>0){
            cartService.batchAddCartProduct(carts);
        }
        List<Product> productList = cartService.findCartProduct(user.getUserId());
        if(productList.size()>5){
            session.setAttribute("carts", productList.subList(0, 5));
        } else {
            session.setAttribute("carts", productList);
        }
        return "redirect:/cart.htm";
    }

    /**
     * 将购物车里的商品移入收藏夹
     * @param cartIds
     * @param session
     * @return
     */
    @RequestMapping("/moveInCollect")
    @ResponseBody
    public String moveInCollect(@RequestParam("cartIds[]") Integer[] cartIds, HttpSession session){
        // 拿到需要删除的购物车实体
        List<Cart> carts = cartService.batchFindCartDataByCartId(cartIds);
        User user = (User) session.getAttribute("user");
        for (Cart cart : carts) {
            // 验证并收藏
            CollectProduct collectProduct = productService.checkUserCollectProduct(user.getUserId(), cart.getPid());
            if(null == collectProduct){
                productService.collectProduct(user.getUserId(), cart.getPid());
            }
        }
        // 删除这些购物车记录
        cartService.batchDeleteCartRow(cartIds);
        List<Product> productList = cartService.findCartProduct(user.getUserId());
        if(productList.size()>5){
            session.setAttribute("carts", productList.subList(0, 5));
        } else {
            session.setAttribute("carts", productList);
        }
        return "success";
    }

    /**
     * 迷你购物车，获得下一级商品
     * @param cartId
     * @return
     */
    @SneakyThrows
    @RequestMapping(value = "/getNextCp", method = RequestMethod.POST)
    @ResponseBody
    public String getNextCartProduct(@RequestParam("cartId") Integer cartId){
        Product cartProduct = cartService.findNextCartProductByCartId(cartId);
        if(null == cartProduct){
            return "no";
        }
        ObjectMapper mapper = new ObjectMapper();
        return mapper.writeValueAsString(cartProduct);
    }

}
